package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品
     * @param dto
     */
    @Override
    @Transactional   // 开启事务（涉及到两张表同时进行）
    public void addDish(DishDTO dto) {
        log.info("新增菜品：{}", dto);
        //1.补充基础属性，存入dish（已用AOP实现了，直接传即可）
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.insert(dish);


        log.info("菜品id：{}", dish.getId());

        //2.拿出菜品的口味数据，存入dish_flavor
        List<DishFlavor> dishFlavors = dto.getFlavors();
        //判断有没有传入口味数据
        if(dishFlavors != null && dishFlavors.size() > 0){
            //补充菜品id
            dishFlavors.forEach(dishFlavor ->
                    dishFlavor.setDishId(dish.getId()));
            log.info("菜品口味数据：{}", dishFlavors);
            dishFlavorMapper.insertBatch(dishFlavors);
        }

    }

    /**
     * 菜品分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        //1.设置分页参数
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        //2.调用Mapper分页查询,强转返回类型
        Page<DishVO> page = dishMapper.list(dto);

        //3.返回结果
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除
     * @param ids
     */
    @Transactional  //开启事务
    @Override
    public void delete(List<Long> ids) {
        //1.删除之前，判断当前菜品状态，起售中不允许删除
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //2.还要判断删除的菜品是否被套餐关联了，套餐关联了，不允许删除
        Integer count = setmealDishMapper.countByDishId(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.删除菜品基本信息dish表
        dishMapper.deleteBatch(ids);

        //4.删除菜品口味信息dish_flavor表
        dishFlavorMapper.deleteBatch(ids);
    }

    /**
     * 根据id查询菜品和对应的口味信息
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //1.根据id查询菜品数据
        Dish dish = dishMapper.selectById(id);

        //判断是否存在这个菜品（后续可以改成常量）
        if(dish == null){
            throw new DeletionNotAllowedException(MessageConstant.DISH_NOT_FOUND);
        }
        //2.查询菜品口味数据
        List<DishFlavor> dishFlavors =  dishFlavorMapper.selectByDishId(id);

        //3.组装DishVO并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);

        dishVO.setFlavors(dishFlavors);
        log.info("菜品数据：{}", dishVO);
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dto
     */
    @Transactional //开启事务
    @Override
    public void update(DishDTO dto) {
        //1.补充基础属性（AOP）
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);

        //2.菜品表数据更新(dish)
        dishMapper.update(dish);

        //3.菜品口味表数据更新(dish_flavors)
        //口味数据可能增加，删除，也可能修改，直接删除所有，重新插入
        dishFlavorMapper.deleteByDishId(dto.getId());

        List<DishFlavor> flavors = dto.getFlavors();
        if(flavors != null && flavors.size() > 0){
            //关联菜品id
            flavors.forEach(flavor ->
                    flavor.setDishId(dto.getId()));
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 根据分类id查询菜品
     * @param id
     * @return
     */
    @Override
    public List<Dish> listById(Long id) {
        List<Dish> dish = dishMapper.listById(id);
        log.info("菜品数据：{}", dish);
        return dish;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listBy(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 批量起售停售
     * @param status
     * @param id
     */
    @Override
    public void setStatus(Integer status, Long id) {
        log.info("批量起售停售：{}", id);
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        log.info("菜品数据：{}", dish);
        dishMapper.update(dish);
    }
}
